package com.xinqi.modules.prepare.question.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.ImmutableList;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.modules.prepare.question.convert.PrepareQuestionFolderConvert;
import com.xinqi.modules.prepare.question.domain.PrepareQuestionFolderEntity;
import com.xinqi.modules.prepare.question.dto.req.PrepareFolderQuestionSortDTO;
import com.xinqi.modules.prepare.question.dto.req.PrepareJoinQuestionFolderDTO;
import com.xinqi.modules.prepare.question.dto.req.PrepareQuestionFolderCreateDTO;
import com.xinqi.modules.prepare.question.dto.req.PrepareQuestionFolderDeleteDTO;
import com.xinqi.modules.prepare.question.dto.req.PrepareQuestionFolderIsExistNameDTO;
import com.xinqi.modules.prepare.question.dto.req.PrepareQuestionFolderQueryDTO;
import com.xinqi.modules.prepare.question.dto.req.PrepareQuestionFolderUpdateDTO;
import com.xinqi.modules.prepare.question.dto.rsp.PrepareQuestionFolderResultDTO;
import com.xinqi.modules.prepare.question.manager.PrepareQuestionFolderManager;
import com.xinqi.modules.prepare.question.manager.PrepareQuestionFolderRefManager;
import com.xinqi.modules.prepare.question.service.PrepareQuestionFolderService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 备课区试题夹服务层实现
 *
 * @author: system
 * @date: 2023/03/19
 */
@Validated
@Service("prepareQuestionFolderService")
@RequiredArgsConstructor
public class PrepareQuestionFolderServiceImpl implements PrepareQuestionFolderService {
    private final PrepareQuestionFolderConvert prepareQuestionFolderConvert;
    private final PrepareQuestionFolderManager prepareQuestionFolderManager;
    private final PrepareQuestionFolderRefManager prepareQuestionFolderRefManager;

    /**
     * 分页查询 备课区试题夹数据
     */
    @Override
    @DS("slaver")
    public PageInfo<PrepareQuestionFolderResultDTO> page(Param pageable, PrepareQuestionFolderQueryDTO query) {
        IPage<PrepareQuestionFolderEntity> page = prepareQuestionFolderManager.page(Pages.page(pageable), wrapper(query));
        return Pages.convert(page, prepareQuestionFolderConvert::convert);
    }

    /**
     * 查询 备课区试题夹数据
     */
    @Override
    public List<PrepareQuestionFolderResultDTO> find(PrepareQuestionFolderQueryDTO query) {
        return prepareQuestionFolderManager.list(wrapper(query)).stream()
            .map(prepareQuestionFolderConvert::convert).collect(Collectors.toList());
    }

    private LambdaQueryWrapper<PrepareQuestionFolderEntity> wrapper(PrepareQuestionFolderQueryDTO query) {
        LambdaQueryWrapper<PrepareQuestionFolderEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(PrepareQuestionFolderEntity::getId, v));
        Queries.accept(query.getPrepareId(), v -> wrapper.eq(PrepareQuestionFolderEntity::getPrepareId, v));
        Queries.accept(query.getName(), v -> wrapper.like(PrepareQuestionFolderEntity::getName, v));
        return wrapper;
    }

    /**
     * 根据id查询 备课区试题夹数据
     */
    @Override
    public PrepareQuestionFolderResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return Optional.ofNullable(prepareQuestionFolderManager.findById(id)).map(prepareQuestionFolderConvert::convert).orElse(null);
    }

    /**
     * 新增 备课区试题夹数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(@Valid PrepareQuestionFolderCreateDTO dto) {
        PrepareQuestionFolderEntity entity = prepareQuestionFolderConvert.create(dto);
        CommonErrors.BAD_REQUEST.check(!isExistName(dto.getPrepareId(), dto.getName(), null), "试题夹名称已存在");
        prepareQuestionFolderManager.save(entity);
        return entity.getId();
    }

    /**
     * 根据id修改 备课区试题夹数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(@Valid PrepareQuestionFolderUpdateDTO dto) {
        PrepareQuestionFolderEntity old = Optional.ofNullable(prepareQuestionFolderManager.getById(dto.getId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        PrepareQuestionFolderEntity entity = prepareQuestionFolderConvert.update(dto);
        CommonErrors.BAD_REQUEST.check(!isExistName(old.getPrepareId(), dto.getName(), dto.getId()), "试题夹名称已存在");
        return prepareQuestionFolderManager.updateById(entity);
    }

    @Override
    public Boolean isExistName(@Valid PrepareQuestionFolderIsExistNameDTO dto) {
        return isExistName(dto.getPrepareId(), dto.getName(), dto.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean isExistName(Long prepareId, String name, Long oldId) {
        return prepareQuestionFolderManager.isExistName(prepareId, name, oldId);
    }


    /**
     * 根据id删除 备课区试题夹数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(@Valid PrepareQuestionFolderDeleteDTO dto) {
        return deleteById(dto.getId());
    }

    /**
     * 根据id删除 备课区试题夹数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        deleteRefData(ImmutableList.of(id));
        return prepareQuestionFolderManager.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(Long prepareId, List<Long> ids) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(prepareId), "备课区ID不能为空");
        CommonErrors.BAD_REQUEST.check(CollectionUtils.isNotEmpty(ids), "课题id列表不能为空");
        boolean b = prepareQuestionFolderManager.removeByIds(ids);
        deleteRefData(ids);
        return b;
    }

    private void deleteRefData(List<Long> folderIds) {
        prepareQuestionFolderRefManager.deletedByFolderIds(folderIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean joinQuestionFolder(@Valid PrepareJoinQuestionFolderDTO dto) {
        return prepareQuestionFolderRefManager.joinQuestionFolder(dto.getPrepareId(), dto.getQuestionFolderId(), dto.getQuestionIds());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeQuestionFolder(@Valid PrepareJoinQuestionFolderDTO dto) {
        return prepareQuestionFolderRefManager.removeQuestionFolder(dto.getPrepareId(), dto.getQuestionFolderId(), dto.getQuestionIds());
    }

    @Override
    public Boolean sortFolderQuestion(@Valid PrepareFolderQuestionSortDTO dto) {
        return prepareQuestionFolderRefManager.sortFolderQuestion(dto.getPrepareId(), dto.getQuestionFolderId(), dto.getSorts());
    }
}
